package com.zzty.zzlp.serviceimpl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zzty.zzlp.dao.TeamExamTransationMapper;
import com.zzty.zzlp.dao.UserDao;
import com.zzty.zzlp.entity.TeamExamTransation;
import com.zzty.zzlp.entity.User;
import com.zzty.zzlp.service.TeamExamTransationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class TeamExamTransationServiceImpl implements TeamExamTransationService {

    @Autowired
    TeamExamTransationMapper teamExamTransationMapper;

    @Autowired
    UserDao UserDao;

    public boolean judgeTotalTime(Integer examId, String userIds) {
        TeamExamTransation tet = teamExamTransationMapper.getInfoByExamIdandUserIds(examId, userIds);
        Integer totalTime = tet.getTotalTime();
        if (totalTime != null) {
            return true;

        } else {
            return false;
        }
    }

    public Integer searchTotalTime(Integer examId, String userIds) {
        String nowTime = getSysTime();
        String ntimes[] = nowTime.split(":");
        Integer nhour = Integer.parseInt(ntimes[0]);
        Integer nmin = Integer.parseInt(ntimes[1]);
        Integer nsecond = Integer.parseInt(ntimes[2]);
        Integer nseconds = nhour * 60 * 60 + nmin * 60 + nsecond;
        TeamExamTransation tet = teamExamTransationMapper.getInfoByExamIdandUserIds(examId, userIds);
        String startTime = tet.getStartTime();
        String stimes[] = startTime.split(":");
        Integer shour = Integer.parseInt(stimes[0]);
        Integer smin = Integer.parseInt(stimes[1]);
        Integer ssecond = Integer.parseInt(stimes[2]);
        Integer sseconds = shour * 60 * 60 + smin * 60 + ssecond;
        Integer totalTime = nseconds - sseconds;
        Integer min = totalTime / 60;
        return min;
    }

    public void updateTotalTime(Integer examId, String userIds) {
        int min = searchTotalTime(examId, userIds);
        TeamExamTransation tet = teamExamTransationMapper.getInfoByExamIdandUserIds(examId, userIds);
        tet.setTotalTime(min);
        teamExamTransationMapper.updateTotaiTime(tet);

    }

    public String getSysTime() {
        Calendar now = Calendar.getInstance();
        String systime = now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE) + ":"
                + now.get(Calendar.SECOND);
        return systime;
    }

    public String searchStateToStartTime(Integer examId, String userIds, Integer userId) {
        TeamExamTransation tet = teamExamTransationMapper.getInfoByExamIdandUserIds(examId, userIds);
        String state = tet.getState();
        String uids[] = userIds.split("\\|");
        String teamiud = "";
        String suserid = userId + "";
        System.out.println("uids.length:" + uids.length);
        if (uids.length != 1) {
            for (int i = 0; i < uids.length; i++) {
                if (!suserid.equals(uids[i])) {
                    teamiud = uids[i];
                }
            }
            if ((state == null) || ("".equals(state)) || ("NULL".equals(state))) {
                tet.setState(suserid);
                teamExamTransationMapper.updateStateByExamIdAndUserIds(tet);
                String error = "请_等_待";
                return error;

            } else if (teamiud.equals(state)) {
                tet.setState(userIds);
                teamExamTransationMapper.updateStateByExamIdAndUserIds(tet);
                updateStartTime(examId, userIds, userId);
                TeamExamTransation tmp = teamExamTransationMapper.getInfoByExamIdandUserIds(examId, userIds);
                String startTime = tmp.getStartTime();
                return startTime;

            } else if (suserid.equals(state)) {
                String error = "请_等_待";
                return error;
            } else {
                String startTime = tet.getStartTime();
                return startTime;
            }
        } else if ((state == null) || ("".equals(state)) || ("NULL".equals(state))) {
            tet.setState(userIds);
            teamExamTransationMapper.updateStateByExamIdAndUserIds(tet);
            ;
            updateStartTime(examId, userIds, userId);
            TeamExamTransation tmp = teamExamTransationMapper.getInfoByExamIdandUserIds(examId, userIds);
            String startTime = tmp.getStartTime();
            return startTime;

        } else {
            String startTime = tet.getStartTime();
            return startTime;

        }
    }

    public void judgeIsValid(Integer examId, String userIds) {
        int valid;
        int min = searchTotalTime(examId, userIds);
        if (min <= 120) {
            valid = 1;

        } else {
            valid = 0;
        }
        TeamExamTransation tet = teamExamTransationMapper.getInfoByExamIdandUserIds(examId, userIds);
        tet.setIsValid(valid);
        teamExamTransationMapper.updateIsValidByExamIdAndUserIds(tet);
        ;
    }

    public String searchUserids(Integer examId, Integer userId) {
        List<String> useridss = new ArrayList<String>();
        String result = "找不到组别";
        String suserid = userId + "";
        // System.out.println("suserid:" + suserid);
        List<TeamExamTransation> tets = teamExamTransationMapper.searchInfoByExamId(examId);
        for (TeamExamTransation tmp : tets) {
            useridss.add(tmp.getUserIds());
        }
        // System.out.println("exameid:" + exameid);
        System.out.println("useridss:" + useridss);
        for (int i = 0; i < useridss.size(); i++) {
            String[] temp = useridss.get(i).split("\\|");
            System.out.println(temp.length);
            for (int j = 0; j < temp.length; j++) {
                if (suserid.equals(temp[j])) {
                    result = useridss.get(i);
                }
            }
        }
        return result;
    }

    public Integer leftTime(Integer examId, String userIds) {
        TeamExamTransation tet = teamExamTransationMapper.getInfoByExamIdandUserIds(examId, userIds);
        String startTime = tet.getStartTime();
        String stimes[] = startTime.split(":");
        int shour = Integer.parseInt(stimes[0]);
        int smin = Integer.parseInt(stimes[1]);
        int ssecond = Integer.parseInt(stimes[2]);
        int sseconds = shour * 60 * 60 + smin * 60 + ssecond;
        int finalseconds = sseconds + 2 * 60 * 60;
        String nowTime = getSysTime();
        String ntimes[] = nowTime.split(":");
        int nhour = Integer.parseInt(ntimes[0]);
        int nmin = Integer.parseInt(ntimes[1]);
        int nsecond = Integer.parseInt(ntimes[2]);
        int nseconds = nhour * 60 * 60 + nmin * 60 + nsecond;
        int leftTime = finalseconds - nseconds;
        return leftTime;
    }

    public String searchState(Integer examId, String userIds) {
        TeamExamTransation tet = teamExamTransationMapper.getInfoByExamIdandUserIds(examId, userIds);
        String state = tet.getState();
        return state;
    }

    public void updateStartTime(Integer examId, String userIds, Integer userid) {
        String uids[] = userIds.split("\\|");
        String teamiud = "";
        String suserid = userid + "";
        for (int i = 0; i < uids.length; i++) {
            if (!suserid.equals(uids[i])) {
                teamiud = uids[i];
            }
        }
        String newuserids = teamiud + "|" + userid;
        TeamExamTransation tet = teamExamTransationMapper.getInfoByExamIdandUserIds(examId, userIds);
        tet.setState(newuserids);
        teamExamTransationMapper.updateStateByExamIdAndUserIds(tet);
        ;
        String startTime = getSysTime();
        tet.setStartTime(startTime);
        teamExamTransationMapper.updateStartTimeByExamIdAndUserIds(tet);
    }

    public boolean judgeStartTime(Integer examId, String userIds) {
        TeamExamTransation tet = teamExamTransationMapper.getInfoByExamIdandUserIds(examId, userIds);
        String startTime = tet.getStartTime();
        // System.out.println(startTime);
        if ((startTime == null) || ("".equals(startTime)) || ("NULL").equals(startTime)) {
            return false;

        } else {
            return true;

        }
    }

    public void updateAnswer(Integer examId, String userIds, String answers) {
        TeamExamTransation tet = teamExamTransationMapper.getInfoByExamIdandUserIds(examId, userIds);
        tet.setAnswers(answers);
        teamExamTransationMapper.updateAnswerByExamIdAndUserIds(tet);
    }

    public void updateScoreAndComment(Integer examId, String userIds, String score, String comment) {
        TeamExamTransation tet = teamExamTransationMapper.getInfoByExamIdandUserIds(examId, userIds);
        tet.setScore(score);
        tet.setComment(comment);
        teamExamTransationMapper.updateScoreByExamIdAndUserIds(tet);
        teamExamTransationMapper.updateCommentByExamIdAndUserIds(tet);
    }

    public List<String> searchAllGroup(Integer examId) {
        List<String> userids = new ArrayList<String>();
        List<TeamExamTransation> tets = teamExamTransationMapper.searchInfoByExamId(examId);
        for (TeamExamTransation tmp : tets) {
            userids.add(tmp.getUserIds());
        }
        return userids;
    }

    public List<String> searchUserIdsName(Integer examId) {
        List<String> userids = new ArrayList<String>();
        List<TeamExamTransation> tets = teamExamTransationMapper.searchInfoByExamId(examId);
        for (TeamExamTransation tmp : tets) {
            userids.add(tmp.getUserIds());
        }
        List<String> userIdsNames = new ArrayList<String>();
        for (int i = 0; i < userids.size(); i++) {
            String userid[] = userids.get(i).split("\\|");

            if (userid.length == 2) {
                int stu1Id = Integer.parseInt(userid[0]);
                int stu2Id = Integer.parseInt(userid[1]);
                try {
                    User stu1 = UserDao.selectUserById(stu1Id);
                    User stu2 = UserDao.selectUserById(stu2Id);
                    String stu1Name = stu1.getDisname();
                    String stu2Name = stu2.getDisname();
                    String userIdsName = stu1Name + "&" + stu2Name;
                    userIdsNames.add(userIdsName);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                int stu1Id = Integer.parseInt(userid[0]);
                try {
                    User stu1 = UserDao.selectUserById(stu1Id);
                    String stu1Name = stu1.getDisname();
                    String userIdsName = stu1Name;
                    userIdsNames.add(userIdsName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return userIdsNames;
    }

    public String searchAnswer(int examId, String userIds) {
        TeamExamTransation tet = teamExamTransationMapper.getInfoByExamIdandUserIds(examId, userIds);
        String answerPath = tet.getAnswers();
        String answer = "";
        if ((answerPath == null) || ("".equals(answerPath))) {
            answer = "无";
            return answer;
        } else {
            try {
                File file = new File(answerPath);
                if (file.isFile() && file.exists()) { // 判断文件是否存在
                    InputStreamReader read = new InputStreamReader(new FileInputStream(file), "GB2312");// 考虑到编码格式
                    BufferedReader bufferedReader = new BufferedReader(read);
                    String lineTxt = null;
                    while ((lineTxt = bufferedReader.readLine()) != null) {
                        // System.out.println(lineTxt);
                        answer += lineTxt + "\r\n";
                    }
                    read.close();
                    return answer;
                } else {
                    System.out.println("找不到指定的文件");
                }
            } catch (Exception e) {
                System.out.println("读取文件内容出错");
                e.printStackTrace();
            }
            return answer;
        }
    }

    public String searchAnswerPath(int examId, String userIds) {
        TeamExamTransation tet = teamExamTransationMapper.getInfoByExamIdandUserIds(examId, userIds);
        if (tet == null) {
            return null;
        }
        return tet.getAnswers();
    }

    public Integer searchValid(int examId, String userIds) {
        TeamExamTransation tet = teamExamTransationMapper.getInfoByExamIdandUserIds(examId, userIds);
        Integer valid = tet.getIsValid();
        return valid;
    }

    public String searchScore(int examId, String userIds) {
        TeamExamTransation tet = teamExamTransationMapper.getInfoByExamIdandUserIds(examId, userIds);
        return tet.getScore();
    }

    public Integer searchTotalTimeById(int examId, String userIds) {
        if (teamExamTransationMapper.getInfoByExamIdandUserIds(examId, userIds) == null) {

            return null;
        }
        TeamExamTransation tet = teamExamTransationMapper.getInfoByExamIdandUserIds(examId, userIds);
        return tet.getTotalTime();
    }

    public void addTeamExamTransation(TeamExamTransation tet) {
        teamExamTransationMapper.addTeamExamTransation(tet);

    }

    public void updateRank(int examId) {
        teamExamTransationMapper.updateRank(examId);
    }

    public String searchWinnerIds(int examId) {
        return teamExamTransationMapper.searchWinnerIds(examId);
    }

    public List<TeamExamTransation> searchInfoByExamId(Integer examId) {
        return teamExamTransationMapper.searchInfoByExamId(examId);
    }

    public List<TeamExamTransation> searchUserIds(String date) {
        return teamExamTransationMapper.searchUserIds(date);
    }

    public Map<String, String> searchIdAndScore(int examId) {
        List<TeamExamTransation> list = teamExamTransationMapper.searchInfoByExamId(examId);
        Map<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < list.size(); i++) {

            map.put(list.get(i).getUserIds() + "", list.get(i).getScore());
            // map.put(rs.getString("Userid"), rs.getString("Score"));

        }
        return map;
    }

    public String searchComment(Integer examId, String userIds) {
        return teamExamTransationMapper.searchComment(examId, userIds);
    }

}
